package net.xuele.learn.IO.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * Created by GaoQingming on 2019/4/12 0012.
 */
public class AsyncTimerServerHandler implements Runnable {
    private int port;

    CountDownLatch latch;
    AsynchronousServerSocketChannel channel;

    public AsyncTimerServerHandler(int port) {
        this.port = port;
        try {
            // 开始通道
            channel = AsynchronousServerSocketChannel.open();
            // 绑定端口
            channel.bind(new InetSocketAddress(this.port));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        latch = new CountDownLatch(1);
        // 连接客户端
        doAccept();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("run here！！");
    }

    private void doAccept() {
        channel.accept(this, new AcceptCompletionHandler());

    }
}
